<template>
    <div>
        <input id="input" type="file" @change="handleFileChange"/>
        <button class="btn" @click="handleUpload">上传</button>
        <pre>{{ output }}</pre>
    </div>
</template>

<script setup>
import {ref} from 'vue';
import axios from 'axios';

const input = document.getElementById('input');
const btn = document.querySelector('.btn');
const fileObj = ref(null);
const output = ref('');

function handleFileChange(e) {
    const [file] = e.target.files;
    fileObj.value = file;
    output.value += `文件获取成功: ${file.name}\n`;
}

function handleUpload() {
    if (!fileObj.value) return;
    const chunkList = createChunk(fileObj.value);
    output.value += `切片列表: ${JSON.stringify(chunkList)}\n`;

    const chunks = chunkList.map(({file}, index) => ({
        file,
        size: file.size,
        percent: 0,
        chunkName: `${fileObj.value.name}-${index}`,
        fileName: fileObj.value.name,
        index: index
    }));

    UploadChunks(chunks);
}

function createChunk(file, size = 5 * 1024 * 1024) {
    const chunkList = [];
    let cur = 0;
    while (cur < file.size) {
        chunkList.push({file: file.slice(cur, cur + size)});
        cur += size;
    }
    return chunkList;
}

function UploadChunks(chunks) {
    const formChunks = chunks.map(({file, fileName, index, chunkName}) => {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('fileName', fileName);
        formData.append('chunkName', chunkName);
        return {
            formData,
            index
        };
    });

    const requestList = formChunks.map(({formData, index}) => {
        return axios.post('http://localhost:3000/upload', formData, {
            onUploadProgress: (progressEvent) => {
                const percentCompleted = Math.round(
                    (progressEvent.loaded * 100) / progressEvent.total
                );
                output.value += `上传进度[${index}]: ${percentCompleted}%\n`;
            }
        });
    });

    Promise.all(requestList).then((responses) => {
        output.value += '所有的片段都传输成功\n';
        mergeChunks();
    });
}

function mergeChunks(size = 5 * 1024 * 1024) {
    axios.post('http://localhost:3000/merge', {
        fileName: fileObj.value.name,
        size: size
    }).then((response) => {
        output.value += `${fileObj.value.name} 合并成功！\n`;
    });
}

</script>

<style scoped>
/* 你可以在这里添加样式 */
</style>